package com.santiao.youxiang.ui.fragment

import android.app.Dialog
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Base64
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.allen.library.shape.ShapeTextView
import com.google.android.material.tabs.TabLayout
import com.santiao.publics.ui.SettingFragment
import com.santiao.youxiang.MainActivity
import com.santiao.youxiang.R
import com.santiao.youxiang.bean.EmailBean
import com.santiao.youxiang.bean.PostBean
import com.santiao.youxiang.bean.RYChargeListBean
import com.santiao.youxiang.database.hleper.PostDatabaseHelper
import com.santiao.youxiang.databinding.FragmentMainBinding
import com.santiao.youxiang.event.XXLEvent
import com.santiao.youxiang.ext.thrillClickListener
import com.santiao.youxiang.ui.activity.EamilDetailActivity
import com.santiao.youxiang.ui.activity.EamilListActivity
import com.santiao.youxiang.ui.activity.EmailWriteActivity
import com.santiao.youxiang.ui.activity.emailSearcheActivity
import com.santiao.youxiang.ui.adapter.AccountItemAdapter
import com.santiao.youxiang.ui.adapter.EmailAdapter
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.nio.charset.Charset
import java.util.Properties
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.Part
import javax.mail.Session
import javax.mail.internet.MimeMessage
import javax.mail.search.FlagTerm
import kotlin.Int
import kotlin.collections.listOf

//import kotlin.io.root


class MainFragment : Fragment(){

    var binding : FragmentMainBinding?=null
//    1 -> "INBOX"
//    2 -> "INBOX"
//    3 -> "已发送"
//    4 -> "草稿箱"
//    5 -> "垃圾邮件"
//    6 -> "已删除"
    var tabTitle=listOf<String>("收件箱", "未读", "已发送", "星标邮件", "草稿箱", "已删除")
    var tabemailcode=listOf<Int>(1,2,3,5,4,6)
//    private val HviewModel: HomeViewModel by viewModels()
    private lateinit var HviewModel: HomeViewModel

    private lateinit var eadapter: EmailAdapter
    private lateinit var Aadapter: AccountItemAdapter

    // 用于控制 Toast 显示的标志
    private var canShowToast = 0

    // 定时器，5秒钟后重置 Toast 显示标志
    private val handler = Handler(Looper.getMainLooper())

    var pageNum=1
    var pageSize=10

    // 添加时间戳检查
    var lastToastTime = 0L

    private lateinit var charge_rv_recycle:RecyclerView
    private lateinit var charge_rl_price:RelativeLayout
    private lateinit var charge_rl_all:RelativeLayout
    private lateinit var home_container: FrameLayout
    private lateinit var charge_tv_selected:TextView
    var chargeData : ArrayList<RYChargeListBean>  = ArrayList()
    var isReshXXL = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding!!.root
//        return inflater.inflate(R.layout.fragment_main,container,false)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView()
        initRv()
        initClick()

        initdata()

    }

    private val refreshRunnable = object : Runnable {
        override fun run() {
            // 这里是你想每 3 分钟执行的代码
            Log.d("AutoTask", "正在执行自动任务...")

            // 执行你的逻辑，比如刷新数据、检查状态等
            // doSomething()

            HviewModel.currentEmailType.value=1
            onRefreshData()

            // 再次延迟 3 分钟（180000 毫秒），实现循环执行
            handler.postDelayed(this, 180000)



        }
    }

    private fun initView(){
        tabTitle.forEach {
            var tab = binding!!.mustMainTab.newTab()
            tab.text = it
            binding!!.mustMainTab.addTab(tab)
        }
//binding!!.mustMainTab.
        HviewModel= MainActivity.HviewModel

//        HviewModel.currentEmailType.value=1
//        onRefreshData()

        if (HviewModel.postList.value.isNullOrEmpty()){

        }else{
            handler.post(refreshRunnable) // 立即启动第一次执行
        }


    }

    fun onRefreshData(){

        if (HviewModel.postList.value.isNullOrEmpty()){
            Toast.makeText(requireContext(), "未绑定邮箱", Toast.LENGTH_SHORT).show()
        }else{
            binding!!.refreshLayout.autoRefresh()
        }


    }

    fun initRv(){


        eadapter=EmailAdapter()


        val layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

        binding!!.rvEmail?.layoutManager = layoutManager
        binding!!.rvEmail?.adapter = eadapter

        eadapter.setEmptyView(R.layout.layout_empty)


        //item整体点击事件
        eadapter?.setOnItemClickListener { adapter, view, position ->

//            val item = adapter.data[position] as HomeCamBean  // 明确类型
//            val userId = item.userId.toString()
//            val chanelId = item.channelID.toString()
//            val token = item.token.toString()
            if (binding!!.mustMainTab.selectedTabPosition==3){
                val bundle=Bundle()
                bundle.putInt("type", 1)
                bundle.putSerializable("email", eadapter.data.get(position))
                EmailWriteActivity.startActivity(requireContext(),bundle)

            }else{
                val bundle=Bundle()
                bundle.putInt("type", 0)
                bundle.putSerializable("email", eadapter.data.get(position))
                EamilDetailActivity.startActivity(requireContext(),bundle)
            }


//            var userIds= adapter.data.get(0)

//            val cam = LitePal.where("userId = ? ", userId).findFirst(liveCam::class.java)
        }

        eadapter!!.setOnItemChildClickListener { _, view, position ->
//            if (view.id == R.id.ll_del) {
//                // 删除逻辑
//                delFromdb(billadapter!!.data.get(position).id.toString())
//                billadapter!!.removeAt(position)
//                billadapter!!.notifyItemRemoved(position)
//
//            }
            val bundle=Bundle()
//            bundle.putInt("type", type)
//            bundle.putSerializable("email", itemData)
//            LZYBaseActivity.forward<EmailDetailActivity>(mContext,bundle)

        }


        Aadapter=AccountItemAdapter()


        val layoutManager2 = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        Log.e("initrv: ", "2")
//        Camadapter

        binding!!.rvAccount?.layoutManager = layoutManager2
        binding!!.rvAccount?.adapter = Aadapter

        Aadapter!!.setOnItemClickListener { adapter, view, position ->

            if (HviewModel.currentPost.value!=Aadapter.data[position].pid){
                val databaseHelper=PostDatabaseHelper(requireContext(),HviewModel)
                val oldCurrent=databaseHelper.getCurrentPost()
                if (oldCurrent!=null){
                    databaseHelper.updatePost(PostBean(oldCurrent.pid,oldCurrent.pAddress,oldCurrent.pCode,false))
                    databaseHelper.updatePost(PostBean(Aadapter.data[position].pid,Aadapter.data[position].pAddress,Aadapter.data[position].pCode,true))
                    HviewModel.currentPost.value=Aadapter.data[position].pid
                }
            }




        }

        Aadapter!!.setOnItemChildClickListener { _, view, position ->



            if (view.id == R.id.iv_del) {
                // 删除逻辑



                deldialog(Aadapter.data.get(position).pid!!.toLong())



            }


        }


    }

    private fun deldialog(pid:Long) {
        val dialog = Dialog(requireContext(), R.style.MyDialog)
//        dialog.setCancelable(false)
//        dialog.setCanceledOnTouchOutside(false)
        dialog.setContentView(R.layout.dialog_del);
//        updateTextColor(dialog)
        dialog.window?.setLayout(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        //底部弹出的Dialog
        dialog.window?.setGravity(Gravity.CENTER);
        var tvtitle=dialog.findViewById<TextView>(R.id.tv_title)
        var tvdes=dialog.findViewById<TextView>(R.id.tv_des)
//        var etdes=dialog.findViewById<EditText>(R.id.et_des)
        var close=dialog.findViewById<ShapeTextView>(R.id.tv_cancel)
//        var checkin=dialog.findViewById<ShapeTextView>(R.id.tv_check)
        var confrim=dialog.findViewById<ShapeTextView>(R.id.tv_confrim)

        dialog.show()

        close.thrillClickListener {
            dialog.cancel()
        }

        confrim.thrillClickListener {
            val databaseHelper=PostDatabaseHelper(requireContext(),HviewModel)
            databaseHelper.deletePost(pid)
            if (HviewModel.postList.value?.size==1){
                val data=databaseHelper.getAllPosts()
                HviewModel.postList.value=data
                HviewModel.currentPost.value=-1
                HviewModel.currentPostType.value="none"
                HviewModel.cleanHome.value=true
                HviewModel.emailList.value= mutableListOf()
            }else{
                val pid=databaseHelper.setFirstPostAsCurrent()
                HviewModel.currentPost.value=pid
            }
            dialog.dismiss()
//            dialog.cancel()
        }


    }


fun initClick(){

    // 设置 DrawerLayout 的监听器
    binding!!.drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
        override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
            // 在侧边栏滑动时，也可以控制其他交互
        }

        override fun onDrawerOpened(drawerView: View) {
            // 当侧边栏打开时，禁用主页面的点击
            binding!!.mainContent.setOnTouchListener { _, _ -> true }
        }

        override fun onDrawerClosed(drawerView: View) {
            // 当侧边栏关闭时，恢复主页面的点击
            binding!!.mainContent.setOnTouchListener(null) // 恢复触摸事件
        }

        override fun onDrawerStateChanged(newState: Int) {
            // 当侧边栏状态变化时触发
        }
    })


    binding!!.mustMainTab.setOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {

            HviewModel.currentEmailType.value=tabemailcode[tab!!.position]
            onRefreshData()

            SettingFragment.adLoad2(1,null,null,context,activity)

        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {

        }

        override fun onTabReselected(tab: TabLayout.Tab?) {

        }
    })

    binding!!.refreshLayout.setOnRefreshListener{
        if (HviewModel.postList.value.isNullOrEmpty()){

            binding!!.refreshLayout.finishRefresh(false)
            Toast.makeText(requireContext(), "未绑定邮箱", Toast.LENGTH_SHORT).show()
            val now = System.currentTimeMillis()
            if (now - lastToastTime > 5000) {


                lastToastTime = now
            }

//            if (canShowToast==0) {
//                Toast.makeText(requireContext(), "未绑定邮箱", Toast.LENGTH_SHORT).show()
//                canShowToast = 1  // 禁止 5 秒内再次显示
//
//                // 5秒后重置标志，允许下次显示 Toast
////                handler.postDelayed({
////                    canShowToast = 0
////                }, 5000)
//
//                // 使用生命周期关联的协程
////                viewLifecycleOwner.lifecycleScope.launch {
////                    delay(5000L)
////                    canShowToast = 0
////                }
//
//            }




            return@setOnRefreshListener
        }
        pageNum=1
        val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
        if (currentPost!=null) {

            tryToLoginEmail(currentPost.pAddress, currentPost.pCode)
        }
    }
    binding!!.refreshLayout.setOnLoadMoreListener {
        if (HviewModel.postList.value.isNullOrEmpty()){
            binding!!.refreshLayout.finishLoadMore(false)

            val now = System.currentTimeMillis()
            if (now - lastToastTime > 5000) {
                Toast.makeText(requireContext(), "未绑定邮箱", Toast.LENGTH_SHORT).show()
                lastToastTime = now
            }

//            if (canShowToast==0) {
//                Toast.makeText(requireContext(), "未绑定邮箱", Toast.LENGTH_SHORT).show()
//                canShowToast = 1  // 禁止 5 秒内再次显示
//
//                // 5秒后重置标志，允许下次显示 Toast
//                // 使用生命周期关联的协程
//                viewLifecycleOwner.lifecycleScope.launch {
//                    delay(5000L)
//                    canShowToast = 0
//                }
//            }

            return@setOnLoadMoreListener
        }
        pageNum++
        val currentPost=HviewModel.postList.value?.first { its -> its.pid== HviewModel.currentPost.value }
        if (currentPost!=null) {
            tryToLoginEmail(currentPost.pAddress, currentPost.pCode)

        }
    }

    binding!!.ivOpen.thrillClickListener {
        binding!!.drawerLayout.open()
    }

    binding!!.llItem1.thrillClickListener {
        binding!!.drawerLayout.close()
    }

    binding!!.etSearch.thrillClickListener {
        if (HviewModel.postList.value.isNullOrEmpty()){
            Toast.makeText(requireContext(), "请先添加邮箱~", Toast.LENGTH_SHORT).show()
            return@thrillClickListener
        }else
        emailSearcheActivity.startActivity(requireContext())

    }

    for (i in 2..6) {
        // 根据名称动态获取资源 id
        val resId = resources.getIdentifier("ll_item$i", "id", requireActivity().packageName)
//        val resIdtv = resources.getIdentifier("tv_month$i", "id", requireActivity().packageName)
        // findViewById 或者如果你用的是 ViewBinding 用 binding.root.findViewById(...)
        val thView = this.view?.findViewById<LinearLayout>(resId) ?: continue
//        val monthtv = findViewById<TextView>(resIdtv) ?: continue
        var tabemailcode=listOf<Int>(1,2,3,5,4,6)
       thView.thrillClickListener {
           EamilListActivity.startActivity(requireContext(),tabemailcode[i-1].toString())
        }

    }
    val bundle=Bundle()
    bundle.putInt("type", 0)
//    bundle.putSerializable("email", eadapter.data.get(position))
//    EmailWriteActivity.startActivity(requireContext(),bundle)

    binding!!.ivWrite.thrillClickListener {
//        EmailWriteActivity.startActivity(requireContext(),bundle)
        var mainActivity = requireActivity() as MainActivity
        mainActivity.goTow();
//        MainActivity.goTow()
    }

    binding!!.ivAdd.thrillClickListener {

        if (HviewModel.postList.value.isNullOrEmpty()){
            Toast.makeText(requireContext(), "请先添加邮箱~", Toast.LENGTH_SHORT).show()
            return@thrillClickListener
        }else
            EmailWriteActivity.startActivity(requireContext(),bundle)

    }

//    binding!!.ivTask1.thrillClickListener {
//
//        Task1Activity.startActivity(requireContext(),"1")
//
//    }
//

}

    override fun onResume() {
        super.onResume()
        // 获取第一个 Tab


    }

    fun initdata(){

        HviewModel.postList.observe(viewLifecycleOwner){list->
            Log.e("initdata: ",list.toString() )


            Aadapter.data.clear()
            Aadapter.setList(list)
//            if (Aadapter.data.isNullOrEmpty()){
//
//            }else binding!!.llAccount.visibility= View.VISIBLE

            Aadapter.notifyDataSetChanged()

        }

        HviewModel.currentPost.observe(viewLifecycleOwner){

            Log.e( "initdata: ", it.toString())

            if (it!=-1L){
                val current=HviewModel.postList.value?.first { its-> its.pid==it }
                if (current!=null){
//                    LZYLog.i("lzyemail","当前邮箱:${current.pAddress}")
                    tryToLoginEmail0(current.pAddress,current.pCode)
                }
            }
        }

        HviewModel.emailList.observe(viewLifecycleOwner){
            if (it.isNullOrEmpty()){
//                binding.noEmail.visibility=View.VISIBLE
//                binding.emailRecyclerView.visibility=View.GONE
                eadapter.setEmptyView(R.layout.layout_empty)
            }else{
//                binding.noEmail.visibility=View.GONE
//                binding.emailRecyclerView.visibility=View.VISIBLE
            }
            eadapter.setList(it)
//            binding.emailRecyclerView.adapter=adapter
//            binding.emailRecyclerView.layoutManager=LinearLayoutManager(myActivity,LinearLayoutManager.VERTICAL,false)
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageSimple(t: XXLEvent) {

    }



    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        handler.removeCallbacks(refreshRunnable)
    }

    fun tryToLoginEmail( email: String, authCode: String) {
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录
                val folderName=
                    if (HviewModel.currentPostType.value=="126"||HviewModel.currentPostType.value=="163"){
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿箱"
                            5 -> "垃圾邮件"
                            6 -> "已删除"
                            else -> if (HviewModel.currentPostType.value=="126") "病毒邮件" else "病毒文件夹"
                        }
                    }else if (HviewModel.currentPostType.value=="aliyun") {
                        when(HviewModel.currentEmailType.value){
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "已发送"
                            4 -> "草稿"
                            5 -> "垃圾邮件"
                            6 -> "已删除邮件"
                            else -> "INBOX"
                        }
                    }else{
                        when(HviewModel.currentEmailType.value) {
                            1 -> "INBOX"
                            2 -> "INBOX"
                            3 -> "Sent Messages"
                            4 -> "Drafts"
                            5 -> "Junk"
                            6 -> "Deleted Messages"
                            else -> "INBOX"
                        }
                    }
                val f=store.getFolder(folderName) as IMAPFolder
                store as IMAPStore
                val idMap: MutableMap<String, String> = HashMap()
                idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
                idMap["version"] = "7.26"
                idMap["os"] = "android"
                idMap["os-version"] = "1.0.0"
                idMap["vendor"] = "hello" // 随便写
                idMap["contact"] = "${email}" // 是一个邮箱
                store.id(idMap)
                f.open(Folder.READ_ONLY)  // 打开文件夹（只读模式）
                // 获取所有邮件
                val emails= mutableListOf<EmailBean>()

if (HviewModel.currentEmailType.value==2){
    // 获取未读邮件
    val messages: Array<Message?>? =
        f.search(FlagTerm(Flags(Flags.Flag.SEEN), false))
}
// 获取邮件消息数组


                var getType=0//0代表不足获取  1代表完整获取  -1表示空获取
                if (f.messageCount>0){
                    //获取所有邮件

                    val messages: Array<Message> = if (HviewModel.currentEmailType.value == 2) {
                        // 使用 search 搜索未读邮件（SEEN == false）
                        val unseenFlag = FlagTerm(Flags(Flags.Flag.SEEN), false)
                        val allUnreadMessages = f.search(unseenFlag)

                        // 分页处理
                        val totalCount = allUnreadMessages.size
                        val startIndex = if (pageNum * pageSize > totalCount) 0 else totalCount - pageNum * pageSize
                        val endIndex = totalCount - (pageNum - 1) * pageSize

                        if (startIndex <= 0) {
                            getType = 0
                            allUnreadMessages.takeLast(endIndex).toTypedArray()
                        } else {
                            getType = 1
                            allUnreadMessages.slice(startIndex until endIndex).toTypedArray()
                        }
                    } else {
                        // 原始 getMessages 方式（支持分页）
                        if (f.messageCount - pageSize * pageNum <= 0) {
                            getType = 0
                            f.getMessages(1, f.messageCount - (pageNum - 1) * pageSize)
                        } else {
                            getType = 1
                            f.getMessages(f.messageCount - pageSize * pageNum + 1, f.messageCount - (pageNum - 1) * pageSize)
                        }
                    }

                   /* val messages =
                        if (HviewModel.currentEmailType.value==2){
                            f.search(FlagTerm(Flags(Flags.Flag.SEEN), false)) as? Array<Message> ?: arrayOf()
                        }
                    else{
                            if (f.messageCount-pageSize*pageNum<=0) {
                                getType=0
//                            LZYLog.i("lzyemailget","form 1 to ${f.messageCount-(pageNum-1)*pageSize}")
                                f.getMessages(1,f.messageCount-(pageNum-1)*pageSize)
                            }
                            else {
                                getType=1
//                            LZYLog.i("lzyemailget","pageNum:$pageNum,messageCount:${f.messageCount}")
//                            LZYLog.i("lzyemailget","form ${f.messageCount - pageSize*pageNum + 1} to ${f.messageCount-(pageNum-1)*pageSize}")
                                f.getMessages(f.messageCount - pageSize*pageNum + 1, f.messageCount-(pageNum-1)*pageSize)
                            }

                    }*/

                    // 输出邮件内容
                    for (message in messages) {
                        message as MimeMessage
                        val emailFrom=decodeBase64AndKeepEmail(message.from.joinToString(", ")).split(" ")
//                        LZYLog.i("lzyemailget","type:${message.contentType}")
                        val contentm= getMailContent(message,true)
                        emails.add(
                            EmailBean(
                                f.getUID(message),
                                emailFrom[0],
                                if (emailFrom.size==1) "<${emailFrom[0]}>" else emailFrom[1],
                                decodeBase64AndKeepEmail(
                                    message.getRecipients(Message.RecipientType.TO)
                                        .joinToString(", ")
                                ),
                                message.sentDate,
                                message.subject,
                                contentm?:""
                            )
                        )
                    }
                }else{
                    getType=-1
                }
                withContext(Dispatchers.Main) {
                    emails.reverse()
                    when(getType){
                        -1 -> {
                            binding!!.refreshLayout.setNoMoreData(true)
                        }

                        0 -> {
                            binding!!.refreshLayout.setNoMoreData(true)
                        }

                        1 -> {
                            binding!!.refreshLayout.setNoMoreData(false)
                        }

                    }
                    if (pageNum==1)
                        HviewModel.emailList.value=emails
                    else{
                        eadapter.addData(emails)
                    }
                }
                // 完成操作后关闭文件夹
                f.close(false)
                store.close()
                withContext(Dispatchers.Main) {
                    if (pageNum==1) {
                        binding!!.refreshLayout.finishRefresh()
//                        LZYLog.i("lzyemailget", "停止刷新")
                    }
                    else {
                        binding!!.refreshLayout.finishLoadMore()
//                        LZYLog.i("lzyemailget", "停止加载更多")
                    }
//                    Toast.makeText(requireContext(),"获取邮件信息成功~", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：登录连接失败")
                withContext(Dispatchers.Main) {
                    if (pageNum==1) {
                        binding!!.refreshLayout.finishRefresh()
//                        LZYLog.i("lzyemailget", "停止刷新")
                    }
                    else {
                        binding!!.refreshLayout.finishLoadMore()
//                        LZYLog.i("lzyemailget", "停止加载更多")
                    }
                    Toast.makeText(requireContext(),"获取邮件信息失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    fun decodeBase64AndKeepEmail(encodedString: String): String {
        // 正则表达式用于匹配 Base64 编码部分，且不区分大小写
        val regex = "=\\?(?i)utf-8\\?b\\?([^?]+)?\\?="

        val matchResults = regex.toRegex().findAll(encodedString)
        val decodedParts = mutableListOf<String>()
        var lastEnd = 0

        // 遍历所有匹配项
        for (match in matchResults) {
            // 添加非 Base64 编码的部分
            decodedParts.add(encodedString.substring(lastEnd, match.range.first))

            // 提取 Base64 编码部分
            val base64Encoded = match.groupValues[1]

            // 解码 Base64 字符串
            val decodedBytes = Base64.decode(base64Encoded, Base64.NO_WRAP)
            val decodedText = String(decodedBytes, Charset.forName("UTF-8"))

            // 添加解码后的文本
            decodedParts.add(decodedText)

            lastEnd = match.range.last + 1
        }

        // 如果还有剩余的部分，直接添加
        decodedParts.add(encodedString.substring(lastEnd))

        return decodedParts.joinToString("")
    }

    @Throws(Exception::class)
    fun getMailContent(part: Part, first: Boolean = true): String {
        val bodyText = StringBuilder()
        val contentType: String = part.contentType.lowercase()

        val isAttachment = contentType.contains("name=") || Part.ATTACHMENT.equals(part.disposition, true)

        when {
            part.isMimeType("text/plain") && !isAttachment -> {
                if (first) return part.content as String
                bodyText.append(part.content as String)
            }

            part.isMimeType("text/html") && !isAttachment -> {
                bodyText.append(part.content as String)
            }

            part.isMimeType("multipart/*") -> {
                val multipart = part.content as Multipart
                for (i in 0 until multipart.count) {
                    bodyText.append(getMailContent(multipart.getBodyPart(i), false))
                }
            }

            part.isMimeType("message/rfc822") -> {
                return getMailContent(part.content as Part, false)
            }
        }
        return bodyText.toString()
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun tryToLoginEmail0( email: String, authCode: String) {
        val loadingDiaLog= LoadingDiaLog(requireContext(),"连接中...")
        loadingDiaLog.show()
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录

                // 获取所有文件夹
                val folder = store.defaultFolder
                val folders = folder.list("*")  // 获取所有文件夹，包括子文件夹
                for (f in folders) {
//                    LZYLog.i("lzyemailtest","${f.name}")
//                    store as IMAPStore
//                    val idMap: MutableMap<String, String> = HashMap()
//                    idMap["name"] = "mail poster" // 这里是一个姓名，可以随便写
//                    idMap["version"] = "7.26"
//                    idMap["os"] = "android"
//                    idMap["os-version"] = "1.0.0"
//                    idMap["vendor"] = "hello" // 随便写
//                    idMap["contact"] = "${email}" // 是一个邮箱
//                    store.id(idMap)
                    if (imapHost == "imap.aliyun.com")
                        f.open(Folder.READ_ONLY)  // 打开文件夹（只读模式）
//                    when (f.name) {
//                        "INBOX" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunGetNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunGetNum.text = "${f.messageCount}"
//                        }
//
//                        "草稿箱", "Drafts" , "草稿" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunKeepNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunKeepNum.text = "${f.messageCount}"
//                        }
//
//                        "已发送", "Sent Messages" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunSendNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunSendNum.text = "${f.messageCount}"
//                        }
//
//                        "已删除", "Deleted Messages" , "已删除邮件"-> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunDelNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunDelNum.text = "${f.messageCount}"
//                        }
//
//                        "垃圾邮件", "Junk" -> {
//                            if (imapHost == "imap.aliyun.com")
//                                binding.postFunTrashNum.text = "${f.messages.size}"
//                            else
//                                binding.postFunTrashNum.text = "${f.messageCount}"
//                        }
//
//                        "病毒文件夹", "病毒邮件" -> {
//                            binding.postFunBadNum.text = "${f.messageCount}"
//                        }
//                    }
//                    f.close()
                }
                store.close()
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
//                    Toast.makeText(requireContext(),"连接成功~", Toast.LENGTH_SHORT).show()
                    if (HviewModel.currentEmailType.value==6&&imapHost == "imap.qq.com") {
                        HviewModel.currentEmailType.value=1
                    }
                    when (domain) {
                        "126.com" -> {
                            HviewModel.currentPostType.value="126"
                        }

                        "163.com" -> {
                            // 对136.com进行处理
                            HviewModel.currentPostType.value="163"
                        }

                        "qq.com" -> {
                            // 对qq.com进行处理
                            HviewModel.currentPostType.value="qq"
                        }

                        else -> {
                            HviewModel.currentPostType.value="aliyun"
                        }
                    }
                    onRefreshData()
                }
            } catch (e: Exception) {
                e.printStackTrace()
//                LZYLog.i("lzyemail", "邮件：登录连接失败")
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(requireContext(),"连接失败！", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }




}
